from sqlalchemy import Column, Integer, String, ForeignKey, Table
from sqlalchemy.orm import relationship, backref

from db_util import Base, Session, engine

news_tag = Table(
    't_news_tag',
    Base.metadata,
    Column('news_id', Integer, ForeignKey('t_news.id'), primary_key=True),
    Column('tag_id', Integer, ForeignKey('t_tag.id'), primary_key=True)
)


class News(Base):
    __tablename__ = 't_news'
    id = Column(Integer, primary_key=True, autoincrement=True)
    title = Column(String(32), nullable=False)
    tags = relationship('Tag', backref='news', secondary=news_tag)

    def __repr__(self):
        return f'<News: id={self.id} title={self.title}>'


class Tag(Base):
    __tablename__ = 't_tag'
    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String(32), nullable=False)

    # news = relationship('News',backref='tags',secondary = news_tag)

    def __repr__(self):
        return f'<Tag: id={self.id} name={self.name}>'

def create_data():
    news1 = News(title='Python更新了！')
    news2 = News(title='SQLAlchemy功能又强大了！')
    tag1 = Tag(name='IT新闻')
    tag2 = Tag(name='科学技术')

    news1.tags.append(tag1)
    news1.tags.append(tag2)
    news2.tags.append(tag1)
    news2.tags.append(tag2)

    with Session() as ses:
        ses.add(news1)
        ses.add(news2)
        ses.commit()

def query_data():
    with Session() as ses:
        new1 = ses.query(News).first()
        print(new1.tags)

if __name__ == '__main__':
    # Base.metadata.create_all(engine)
    # create_data()
    query_data()